package com.fuershiye.woman.monitor.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fuershiye.woman.monitor.beans.IdNameSname;
import com.fuershiye.woman.monitor.constants.PermissionEnum;
import com.fuershiye.woman.monitor.model.Permission;
import com.fuershiye.woman.monitor.model.Role;
import com.fuershiye.woman.monitor.service.DepartmentService;
import com.fuershiye.woman.monitor.service.PermissionService;
import com.fuershiye.woman.monitor.service.RoleService;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
//import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping(value = "/manager/role")
public class ManagerRoleController {

    private static final Logger logger = LoggerFactory
            .getLogger(ManagerRoleController.class);

    @Autowired
    RoleService roleService;
    @Autowired
    PermissionService permissionService;
	@Autowired
	DepartmentService departmentService;

//    @RequiresPermissions("manager:rolePermissionList")
    @RequestMapping(value="/permissionList.do")
    public String permissionList(String page,Model model,HttpServletRequest request){
        List<Permission> permissionList = permissionService.list();
        List<IdNameSname> department = departmentService.getAllSnames(null,null,null);
        model.addAttribute("departmentList",department);
        model.addAttribute("permissionList",permissionList);
        return "manager/" + page;
    }
    
//    @RequiresPermissions("manager:roleList")
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public List<Role> list(String name) {
        if(StringUtils.isNotBlank(name)) {
            List<Role> list = roleService.listByName(name);
            return list;
        }
        List<Role> list = roleService.list();
        return list;
    }

//    @RequiresPermissions("manager:roleAdd")
    @RequestMapping(value="/add.do")
    @ResponseBody
    public boolean add(String name, Long department, Long id) {

        if(StringUtils.isBlank(name) || department ==null||department==0){
            logger.info("manager role add is empty! ,{},{}", name,department);
            return false;
        }
        IdNameSname depart = departmentService.find(department);
        if(depart==null){
            logger.info("manager role depart is empty! ,{}", department);
            return false;
        }
        if(id != null) {
            Role role = roleService.get(id);
            role.setName(name);
            role.setDepartment(department);
            role.setDname(depart.getName());
            long now = System.currentTimeMillis();
            Date nowDate = new Date(now);
            role.setCreateTime(nowDate);
            roleService.save(role);
            return true;
        }
        Role role = new Role();
        role.setName(name);
        role.setDepartment(department);
        role.setDname(depart.getName());
        long now = System.currentTimeMillis();
        Date nowDate = new Date(now);
        role.setCreateTime(nowDate);
        roleService.save(role);
        return true;
    }

//    @RequiresPermissions("manager:roleDelete")
    @RequestMapping(value="/delete.do")
    @ResponseBody
    public boolean delete(Long id) {
        Role role = roleService.get(id);
        if(role!=null){
        	roleService.delete(id);
        }
        return true;
    }

//    @RequiresPermissions("manager:roleViewPermissions")
    @RequestMapping(value="/viewPermissions.do")
    @ResponseBody
    public String viewPermissions(Long id) {
        Set<Long> pIds = Sets.newHashSet();
        Role role = roleService.get(id);
        List<Permission> permissions = role.getPermissions();
        for(int i=0;i<permissions.size();i++) {
            pIds.add(permissions.get(i).getId());
        }
        JSONArray roleJson = new JSONArray();
        roleJson.add(pIds);
        return roleJson.toString();
    }

//    @RequiresPermissions("manager:roleAddPermission")
    @RequestMapping(value="/addPermission.do")
    @ResponseBody
    public String addPermission(Long rid, Long pid) {

        Role role = roleService.get(rid);
        if(role==null){
            return "error";
        }

        Permission aimPermission = permissionService.get(pid);
        if(aimPermission==null){
            return "error";
        }

        if(aimPermission.getPermissionCode().equals(PermissionEnum.PERMISSION_AREALIST_PROVINCE.getValue())||
                aimPermission.getPermissionCode().equals(PermissionEnum.PERMISSION_AREALIST_CITY.getValue())||
                aimPermission.getPermissionCode().equals(PermissionEnum.PERMISSION_AREALIST_COUNTY.getValue())){

            String userArea = "";
            for (Permission permission : role.getPermissions()) {
                if(permission==null){
                    continue;
                }
                if(permission.getPermissionCode()==null){
                    continue;
                }

                //用户三种角色只能所属一种。
                //省级别的人员，可查看所有地级市  -查看全省（各地市）
                if(permission.getPermissionCode().equals(PermissionEnum.PERMISSION_AREALIST_PROVINCE.getValue())){
                    userArea = permission.getPermissionCode();
                    break;
                }
                //地市级别的人员，可查看本市所有区县事
                if(permission.getPermissionCode().equals(PermissionEnum.PERMISSION_AREALIST_CITY.getValue())){
                    userArea = permission.getPermissionCode();
                    break;
                }
                //区县级别的人员，可查看本区县数据的上报情况
                if(permission.getPermissionCode().equals(PermissionEnum.PERMISSION_AREALIST_COUNTY.getValue())){
                    userArea = permission.getPermissionCode();
                    break;
                }
            }

            //用户已经有三种权限之一
            if(!StringUtils.isBlank(userArea)){
                return "have";
            }
        }

        List<Permission> permissions = role.getPermissions();
        permissions.add(aimPermission);
        roleService.save(role);
        JSONObject jsonObject = new JSONObject();
        return jsonObject.toJSONString();
    }

//    @RequiresPermissions("manager:roleDeletePermission")
    @RequestMapping(value="/deletePermission.do")
    @ResponseBody
    public String deletePermission(Long rid, Long pid) {
        Role role = roleService.get(rid);
        Permission permission = permissionService.get(pid);
        List<Permission> permissions = role.getPermissions();
        permissions.remove(permission);
        roleService.save(role);
        JSONObject jsonObject = new JSONObject();
        return jsonObject.toJSONString();
    }

}
